﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NaviCar.Servico.Entidades;
using NaviCar.DB.Auxiliar;
using NaviCar.Models;
using System.IO;
using System.Text;

namespace NaviCar.Controllers
{
    public class NavegacaoController :BaseController
    {
        //
        // GET: /Navegacao/
        [Authorize]
        public ActionResult Index()
        {
            return View();
        }

        [Authorize]
        public ActionResult Historico()
        {
            return View();
        }


        [Authorize]
        public ActionResult PesquisaHistorico(int id, string inicio, string fim)
        {
            //HistoricoNavegacao historico = new HistoricoNavegacao { Inicio = new DateTime(2008, 1, 1), Fim = new DateTime(2011, 12, 12), Veiculo = 1 };
            ServicoNavegacao servico = new ServicoNavegacao();
            
            try
            {
                DateTime auxInicio = DateTime.Parse(inicio.Replace("-", "/"));
                DateTime auxFim = DateTime.Parse(fim.Replace("-", "/"));

                string Km = servico.RecuperarArquivoKM(auxInicio, auxFim, id);
                UTF8Encoding uni = new UTF8Encoding();

                byte[] dadosKm = uni.GetBytes(Km.ToCharArray());
                MemoryStream st = new MemoryStream();
                st.Write(dadosKm,0,dadosKm.Length);

                return File(dadosKm, "application/kmz", "teste.kml");

            }
            catch (Exception ex)
            {
                ModelState.AddModelError("",ex.Message);
                return View();
            }

            return View();
        }

        [HttpPost]
        [Authorize]
        public ActionResult Rastrear(int codigo)
        {
            ServicoNavegacao servico = new ServicoNavegacao();

            try
            {
                Rastreamento rastreamento = servico.RecuperarUltimoRegistro(codigo);

                if (rastreamento != null)
                {
                    return Json(new { entidade = rastreamento});
                }
                else
                {
                    return Json(new { msg = string.Empty });
                }
            }
            catch (Exception ex)
            {
                return Json(new { msg = ex.Message });
            }
            

        }

    }
}
